import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
import { LoggingInterceptor } from './shared/interceptors/logging.interceptor';
import { AppLoggerService } from './shared/services/logger.service';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import * as dotenv from 'dotenv';
import * as path from 'path';
import * as fs from 'fs';

// 尝试加载 .env 文件，如果存在的话
const possiblePaths = [
  path.join(__dirname, '..', '.env'),           // 本地开发：dist/.env
  path.join(process.cwd(), '.env'),             // 当前工作目录：项目根目录/.env
  path.join(__dirname, '..', '..', '.env'),     // 服务器：/www/wwwroot/server/text-tags-backend/.env
];

let envLoaded = false;
for (const envPath of possiblePaths) {
  if (fs.existsSync(envPath)) {
    dotenv.config({ path: envPath });
    console.log('📄 Loaded .env file from:', envPath);
    envLoaded = true;
    break;
  }
}

if (!envLoaded) {
  console.log('🚀 Using system environment variables (no .env file found)');
}

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  const logger = new AppLoggerService('Bootstrap');

  // 调试输出关键环境变量（打码）
  const token = process.env.COZE_TOKEN;
  const masked = token ? `${token.slice(0, 6)}...${token.slice(-4)}` : undefined;

  // 配置静态文件服务
  app.useStaticAssets(join(__dirname, '..', 'uploads'), {
    prefix: '/uploads/',
  });
  
  // 配置缩略图静态文件服务
  app.useStaticAssets(join(__dirname, '..', 'uploads', 'thumbnails'), {
    prefix: '/uploads/thumbnails/',
  });

  // 添加全局日志拦截器
  app.useGlobalInterceptors(new LoggingInterceptor());

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );

  app.setGlobalPrefix('api');

  // 配置允许的跨域来源
  const allowedOrigins = [
    'https://news.jsz1234.xyz',
  ];

  // 如果环境变量中配置了额外的域名，也添加进来
  if (process.env.CORS_ORIGIN) {
    const envOrigins = process.env.CORS_ORIGIN.split(',').map(o => o.trim());
    allowedOrigins.push(...envOrigins);
  }

  app.enableCors({
    origin: (origin, callback) => {
      // 允许没有 origin 的请求（如 Postman、curl、服务器端请求）
      if (!origin) {
        callback(null, true);
        return;
      }

      // 允许本地开发环境的所有端口
      // 匹配 http://localhost:端口 或 http://127.0.0.1:端口
      const localPattern = /^https?:\/\/(localhost|127\.0\.0\.1):[0-9]+$/;
      if (localPattern.test(origin)) {
        callback(null, true);
        return;
      }

      // 检查是否在白名单中（生产域名）
      if (allowedOrigins.includes(origin)) {
        callback(null, true);
        return;
      }

      // 允许通过 IP 地址访问（开发和生产环境）
      // 匹配 http://IP:端口 或 http://IP 的格式
      const ipPattern = /^https?:\/\/(\d{1,3}\.){3}\d{1,3}(:\d+)?$/;
      if (ipPattern.test(origin)) {
        callback(null, true);
        return;
      }

      // 不在白名单中且不是本地或 IP 访问
      callback(new Error('Not allowed by CORS'));
    },
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true,
  });

  const port = process.env.PORT || 3000;
  const host = process.env.HOST || '0.0.0.0';
  
  await app.listen(port, host);
  
  logger.success(`Server running on http://${host}:${port}/api`);
  logger.info(`Local access: http://localhost:${port}/api`);
  logger.info(`Environment: ${process.env.NODE_ENV || 'development'}`);
  logger.info(`Database: ${process.env.DB_DATABASE || 'not configured'}`);
}
bootstrap();